package com.my.demos.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.ReturnedMessage;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;

/**
 * @author zhupanlin
 * @version 1.0
 * @description: 消息接收回调接口
 * @date 2023/12/1 19:13
 */
@Slf4j
@Component
public class MyCallBack implements RabbitTemplate.ConfirmCallback, RabbitTemplate.ReturnsCallback {
    
    @Resource
    RabbitTemplate rabbitTemplate;
    
    @PostConstruct
    public void init(){
        rabbitTemplate.setConfirmCallback(this);
        rabbitTemplate.setReturnsCallback(this);
    }
    
    

    /**
     * 交换机确认回调方法
     * 1. 发消息 交换机接收到了 b就为true，否则为false
     * @param correlationData 保存回调消息的ID以及相关信息
     * @param ack 交换机是否收到消息
     * @param cause 失败的原因
     */
    
    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String cause) {
        String id = correlationData != null ? correlationData.getId() : "";
        if (ack){
            log.info("交换机已经接收到ID为:{}的消息", id);
        }else {
            log.info("交换机还未收到ID为:{}的消息, 原因是:{}", id, cause);
        }
        
    }

    // 可以在消息传递过程中不可达目的地时将消息返回给生产者
    // 失败 才进行回退
    @Override
    public void returnedMessage(ReturnedMessage returnedMessage) {
        Message message = returnedMessage.getMessage();
        String exchange = returnedMessage.getExchange();
        String replyText = returnedMessage.getReplyText();
        String routingKey = returnedMessage.getRoutingKey();
        log.error("消息{}, 被交换机{}退回, 退回原因:{}, 路由key:{}",
                new String(message.getBody()), exchange, replyText, routingKey);
    }
}
